/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package it.coraci.anag.gui.people.mr;

import it.coraci.anag.db.sql.controllers.PersonJpaController;
import it.coraci.anag.db.sql.entities.Person;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Persistence;
import javax.swing.DefaultListModel;

/**
 *
 * @author Luca
 */
public class PeopleListModel  extends DefaultListModel<Person>{
    
    public Map<Long,Person> idMap = new HashMap<Long,Person>();
    
    public PeopleListModel() {
        super();
    }
    
    public void refresh(){
        this.removeAllElements();
        PersonJpaController cc = new PersonJpaController(Persistence.createEntityManagerFactory("dbAnagBasePU"));
            List<Person> findPersonEntities = cc.findPersonEntities();
            for (Person person : findPersonEntities) {
                idMap.put(person.getId(), person);
                this.addElement(person);
            }
    }

    @Override
    public void addElement(Person element) {
        super.addElement(element);
         idMap.put(element.getId(), element);
    }
    
    
    
    public void updateEntity(Person newPerson){
        Person oldPerson = idMap.get(newPerson.getId());
        System.out.println("oldPersone name: "+oldPerson.getNome());
        int indexOf = this.indexOf(oldPerson);
        System.out.println("index = "+indexOf);
        this.remove(indexOf);
        this.add(indexOf, newPerson);
    }
    
}
